<?php

class m_website_actions_block_modal_SavePageAsLayoutAction extends m_backoffice_extends_FormModal
{
	public function execute()
	{
        $this->setModalParameters();

        $layouts = $this->getDocumentProvider() ->loadDocuments('modules_website/layout')
                                                ->whereIsEqual('websiteId', $this->getContextWebsite()->getUniqueId())
                                                ->retrieveDocuments($this->getRequestParameter('docLang'));

        if($this->isFormSubmit())
        {
            $values = $this->getFormValues('form');
            $errors = $this->checkForm($values);

            if(count($errors) == 0)
            {
                $page = $this->getDocumentFromRequest();

                /* @var $page m_website_documents_Page */

                if($page->getModel() == 'modules_website/page' && $page->hasTemplateFile())
                {
                    $tempDocService = m_backoffice_services_TempDocService::getInstance();

                    $page = $tempDocService->getTemporaryDocument($page->getUniqueId(), $page->getLang(), true);

                    $layoutXml = $this->getLayoutXml($page);

                    if(isset($values['layout']) && $values['layout'] != '0')
                    {
                        $layout = $this->getDocumentProvider()->getByUniqueId($values['layout'], $this->getRequestParameter('docLang'));
                    }
                    else
                    {
                        $layout = m_website_documents_Layout::createNew();
                        $layout->setLabel($values['label']);
                    }


                    $layout ->setStructure($layoutXml)
                            ->setOriginalLayout($page->getTemplate())
                            ->setWebsiteId($page->getWebsiteId())
                            ->setAuthor($this->getUser()->getLogin())
                            ->save();

                    $this->closeModalAndRefresh();
                }
            }
            else
            {
                $this->addToModel('errors', $errors);
            }
        }

        $this->addToModel('layouts', $layouts);
		$this->setView('success');
	}

    private function checkForm($values)
    {
        $errors = array();

        if(!isset($values['label']) && $values['layout'] == '0' || $values['label'] == '' && $values['layout'] == '0')
        {
            $errors['label'] = f_locale_Manager::getLocale('backoffice.errors.required');
        }

        return $errors;
    }

    private function getLayoutXml($page)
    {
        /* @var $page m_website_documents_Page */
        $xml = f_xml_Xpath::getInstance($page->getTemplateFile())->getElementFromXpath('structure')->asXml();

        $xmlReader = new XMLReader();
        $xmlReader->XML($xml);


        $xmlWriter = new XMLWriter();
        $xmlWriter->openMemory();
        $xmlWriter->setIndent(true);
        $xmlWriter->setIndentString('    ');

        $zoneId = 0;

        $result = '';

        while($xmlReader->read())
        {
            if($xmlReader->nodeType == XMLReader::ELEMENT)
            {
                switch ($xmlReader->name)
                {
                    case 'block':
                        $type = $xmlReader->getAttribute('type');
                        if(!is_null($type) && $type == 'freeContent')
                        {
                            $zoneId++;
                            $blocks = $page->getBlocksByZoneId($zoneId);
                            if(count($blocks) > 0)
                            {
                                foreach($blocks as $block)
                                {
                                    if(isset($block['blockId'])) unset($block['blockId']);
                                    if(isset($block['rawValues'])) unset($block['rawValues']);
                                    $xmlWriter->startElement('block');
                                    foreach($block as $name => $value)
                                    {
                                        $xmlWriter->writeAttribute($name, $value);
                                    }
                                    $xmlWriter->endElement();
                                }
                            }
                            $xmlWriter->startElement('block');
                            if ($xmlReader->hasAttributes)
                            {
                                while ($xmlReader->moveToNextAttribute())
                                {
                                    $xmlWriter->writeAttribute($xmlReader->name, $xmlReader->value);
                                }
                                $xmlReader->moveToElement();
                            }
                            $xmlWriter->endElement();
                        }
                        else
                        {
                            $xmlWriter->startElement($xmlReader->name);
                            if ($xmlReader->hasAttributes)
                            {
                                while ($xmlReader->moveToNextAttribute())
                                {
                                    $xmlWriter->writeAttribute($xmlReader->name, $xmlReader->value);
                                }
                                $xmlReader->moveToElement();

                                if($xmlReader->isEmptyElement)
                                {
                                    $xmlWriter->endElement();
                                }
                            }
                        }
                    break;

                    default:
                            $xmlWriter->startElement($xmlReader->name);
                            if ($xmlReader->hasAttributes)
                            {
                                while ($xmlReader->moveToNextAttribute())
                                {
                                    $xmlWriter->writeAttribute($xmlReader->name, $xmlReader->value);
                                }
                                $xmlReader->moveToElement();

                                if($xmlReader->isEmptyElement)
                                {
                                    $xmlWriter->endElement();
                                }
                            }
                    break;
                }
            }

            if($xmlReader->nodeType == XMLReader::END_ELEMENT)
            {
                $xmlWriter->endElement();
            }
        }

        $result = $xmlWriter->outputMemory(true);
        return $result;
    }
}